/**
 * @auth: sce
 * @date: 1/9/18
 * @desc: 接受两个版本好生成当前版本到目标版本的增量压缩包
 **/

const child_process = require('child_process');
const fs = require('fs');

const patchFile = require('./patchFile');
const createFolder = require('./createFolder');
const {patchPath, bundlePath} = require('./../config');
const zipFolder = require('./zip');
/**
 * 生成相应的目录
 * @param newRelease 目标版本
 */
const makeDir = (originalRelease,newRelease) => {
    const androidPath = `${patchPath}/${newRelease}/android/${originalRelease}`;
    const iosPath = `${patchPath}/${newRelease}/ios/${originalRelease}`;
    createFolder(androidPath);
    createFolder(iosPath);
};


/**
 * 拷贝资源文件
 * @param originalRelease
 * @param newRelease
 */
const copyAssets = async (originalRelease, newRelease) => {
    const androidBundlePath = `${bundlePath}/${newRelease}/android/drawable-mdpi`;
    const iosBundlePath = `${bundlePath}/${newRelease}/ios/assets`;
    const androidPatchPath = `${patchPath}/${newRelease}/android//${originalRelease}`;
    const iosPatchPath = `${patchPath}/${newRelease}/ios//${originalRelease}`;
    if(fs.existsSync(`${androidPatchPath}/drawable-mdpi`)){
        await child_process.exec(`rm -rf ${androidPatchPath}/drawable-mdpi`);
    }
    if(fs.existsSync(`${iosPatchPath}/assets`)){
        await child_process.exec(`rm -rf ${iosPatchPath}/assets`);
    }
    await child_process.exec(`cp -r ${androidBundlePath} ${androidPatchPath}`);
    await child_process.exec(`cp -r ${iosBundlePath} ${iosPatchPath}`);

};

/**
 * 生成bundle的增量文件
 * @param originalRelease
 * @param newRelease
 */

const createPatchFile = (originalRelease, newRelease) => {
    patchFile(
        `${bundlePath}/${originalRelease}/ios/index.ios.bundle`,
        `${bundlePath}/${newRelease}/ios/index.ios.bundle` ,
        `${patchPath}/${newRelease}/ios/${originalRelease}/${originalRelease}-${newRelease}.pat`);
    patchFile(
        `${bundlePath}/${originalRelease}/android/index.android.bundle`,
        `${bundlePath}/${newRelease}/android/index.android.bundle` ,
        `${patchPath}/${newRelease}/android/${originalRelease}/${originalRelease}-${newRelease}.pat`);
};

/**
 * 压缩增量包
 * @param originalRelease
 * @param newRelease
 */
const zipPatchDir = (originalRelease, newRelease) => {
    zipFolder(
        `${patchPath}/${newRelease}/android/${originalRelease}`,
        `${patchPath}/${newRelease}/android/${originalRelease}-${newRelease}.android.pat.zip`);
    zipFolder(
        `${patchPath}/${newRelease}/ios/${originalRelease}`,
        `${patchPath}/${newRelease}/ios/${originalRelease}-${newRelease}.ios.pat.zip`);
};

const start = async (originalRelease, newRelease) => {
    await makeDir(originalRelease, newRelease);
    await copyAssets(originalRelease,newRelease);
    await createPatchFile(originalRelease, newRelease);
    await zipPatchDir(originalRelease, newRelease);
};

module.exports = start;